package com.yx.front.manager;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.yx.front.config.ALiYunOSSConfig;
import com.yx.front.config.global.CommonResult;
import com.yx.front.utils.FileTypeUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author YangXiong
 */
@Component
public class OssFileUpManager {
    private static final String PHOTO = "photo";
    private static final String ERROR = "error";
    @Resource
    private FileTypeUtil fileTypeUtil;
    @Resource
    private OSS ossClient;
    @Resource
    private ALiYunOSSConfig ossConfig;

    public String upload(MultipartFile file) throws UnsupportedEncodingException {
        //校验文件是否是我们允许的类型
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String res = fileTypeUtil.isOneType(type);
        if (ERROR.equals(res)) {
            return type + "格式文件暂时不支持上传";
        }
        //处理中文文件名，防止返回的url不能访问
        String tempFileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        String originalFilename = URLEncoder.encode(tempFileName, "UTF-8") + "." + type;
        // 获取文件输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObjectMetadata meta = new ObjectMetadata();
        //如果是图片类型，设类型
        if (PHOTO.equals(res)) {
            meta.setContentType("image/jpg");
        }
        //文件上传至阿里云OSS
        ossClient.putObject(ossConfig.getBuket(), res + "/" + file.getOriginalFilename(), inputStream, meta);
        // 返回文件上传的路径地址
        return ossConfig.getUrl() + res + "/" + originalFilename;
    }

    public CommonResult<String> download(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置响应头为下载
        response.setContentType("application/x-download");
        // 设置下载的文件名
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
        response.setCharacterEncoding("UTF-8");
        // 文件名以附件的形式下载
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 获取oss的Bucket名称
        String bucketName = ossConfig.getBuket();
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, fileName);
        try {
            // 读取文件内容。
            InputStream inputStream = ossObject.getObjectContent();
            // 把输入流放入缓存流
            BufferedInputStream in = new BufferedInputStream(inputStream);
            ServletOutputStream outputStream = response.getOutputStream();
            // 把输出流放入缓存流
            BufferedOutputStream out = new BufferedOutputStream(outputStream);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            //关闭所有流
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            return CommonResult.fail("系统异常");
        }
        return CommonResult.success("下载中");
    }
}
